package com.tian.code.tool.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.tian.code.tool.Utils;

@Repository
public class TableDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 检查表是否存在
	 * @param tabName
	 * @return
	 */
	public Boolean checkTabIsExist(String tabName) {
		int count = jdbcTemplate.queryForInt("SELECT count(*) FROM user_tables where table_name = ?",
				new Object[] { tabName });

		if (count == 0)
			return false;
		else
			return true;
	}

	public List<String> getAllTableName() {
		List<Map<String, Object>> r = jdbcTemplate.queryForList("SELECT table_name FROM user_tables");
		List<String> l = new ArrayList<String>();
		for (Map<String, Object> map : r) {
			l.add(map.get("table_name").toString());
		}
		return l;
	}

	/**
	 * 获取当前用户所有表注释
	 * 
	 * @return
	 */
	public HashMap<String, String> getTableComments() {

		List<Map<String, Object>> l = jdbcTemplate
				.queryForList("SELECT A.TABLE_NAME, A.COMMENTS FROM USER_TAB_COMMENTS A");

		HashMap<String, String> map = new HashMap<String, String>();

		for (Map<String, Object> m : l) {
			map.put(m.get("TABLE_NAME").toString(), Utils.getNotNullString(m.get("COMMENTS")));
		}

		return map;
	}

	/**
	 * 获取表字段注释
	 * 
	 * @return
	 */
	public HashMap<String, String> getColComments(String tabName) {

		List<Map<String, Object>> l = jdbcTemplate.queryForList(
				"SELECT A.COLUMN_NAME, A.COMMENTS FROM USER_COL_COMMENTS A WHERE TABLE_NAME = ?",
				new Object[] { tabName });

		HashMap<String, String> map = new HashMap<String, String>();

		for (Map<String, Object> m : l) {
			map.put(m.get("COLUMN_NAME").toString(), Utils.getNotNullString(m.get("COMMENTS")));
		}

		return map;
	}

	/**
	 * 获取表字段信息
	 * 
	 * @return
	 */
	public List<Map<String, Object>> geTabColumns(String tabName) {

		return jdbcTemplate.queryForList("SELECT * FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? ORDER BY COLUMN_ID",
				new Object[] { tabName });
	}

	/**
	 * 获取表主键字段详细信息
	 * 
	 * @param tabName
	 * @return
	 */
	public List<String> getTableColKey(String tabName) {
		String sql = "SELECT B.COLUMN_NAME FROM USER_CONSTRAINTS A, USER_CONS_COLUMNS B WHERE A.TABLE_NAME = ? "
				+ "AND A.CONSTRAINT_TYPE = 'P' AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME";
		List<Map<String, Object>> r = jdbcTemplate.queryForList(sql, new Object[] { tabName });
		List<String> l = new ArrayList<String>();
		for (Map<String, Object> map : r) {
			l.add(map.get("COLUMN_NAME").toString());
		}
		return l;
	}

}
